package com.chenyi.web.controller.system;

import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.domain.entity.SysAdminMenu;
import com.chenyi.common.core.domain.entity.SysAdmin;
import com.chenyi.common.core.domain.model.LoginBody;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.framework.web.service.AdminLoginService;
import com.chenyi.framework.web.service.AdminPermissionService;
import com.chenyi.framework.web.service.AdminTokenService;
import com.chenyi.system.service.ISysAdminMenuService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 * 
 * @author wangkh
 */
@RestController
@RequestMapping("/admin")
public class AdminLoginController
{
    @Autowired
    private AdminLoginService loginService;

    @Autowired
    private ISysAdminMenuService menuService;

    @Autowired
    private AdminPermissionService permissionService;

    @Autowired
    private AdminTokenService tokenService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public ResponseEntity<Object> login(@RequestBody LoginBody loginBody)
    {
        Map<String,Object> data = Maps.newHashMap();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        data.put(Constants.TOKEN, token);
        return ResponseEntity.ok(data);
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public ResponseEntity<Object> getInfo()
    {
        LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
        SysAdmin user = loginUser.getAdmin();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String,Object> data = Maps.newHashMap();
        data.put("user", user);
        data.put("roles", roles);
        data.put("permissions", permissions);
        return ResponseEntity.ok(data);
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public ResponseEntity<Object> getRouters()
    {
        LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
        // 用户信息
        SysAdmin user = loginUser.getAdmin();
        List<SysAdminMenu> menus = menuService.selectAdminMenuTreeByAdminId(user.getAdminId());
        return ResponseEntity.ok(menuService.buildAdminMenus(menus));
    }
}
